const userModel = require('../models/userModel');
const { generateToken } = require('../utils/token');
const { success, notFound, serverError, conflict } = require('../utils/response');

/**
 * 用户注册
 */
const register = async (req, res) => {
  try {
    const { username, email, password } = req.body;
    
    // 验证输入
    if (!username || !email || !password) {
      return notFound(res, '用户名、邮箱和密码都是必填项');
    }
    
    // 检查邮箱是否已存在
    const existingUser = await userModel.findUserByEmail(email);
    if (existingUser) {
      return conflict(res, '该邮箱已被注册');
    }
    
    // 创建用户
    const userId = await userModel.createUser(username, email, password);
    const token = generateToken(userId);
    
    success(res, { 
      token,
      user: {
        id: userId,
        username,
        email
      }
    }, '注册成功');
  } catch (err) {
    console.error('注册错误:', err);
    serverError(res, '注册失败');
  }
};

/**
 * 用户登录
 */
const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    
    // 验证输入
    if (!email || !password) {
      return notFound(res, '邮箱和密码都是必填项');
    }
    
    // 查找用户
    const user = await userModel.findUserByEmail(email);
    if (!user) {
      return notFound(res, '用户不存在');
    }
    
    // 验证密码
    const isMatch = await userModel.comparePassword(password, user.password);
    if (!isMatch) {
      return notFound(res, '密码错误');
    }
    
    // 生成token
    const token = generateToken(user.id);
    
    success(res, { 
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar
      }
    }, '登录成功');
  } catch (err) {
    console.error('登录错误:', err);
    serverError(res, '登录失败');
  }
};

module.exports = {
  register,
  login
};